package com.spark.lola.controller.logistics;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.spark.lola.logistics.constant.LogisticsConstant;
import com.spark.lola.logistics.entity.DriverInfo;
import com.spark.lola.logistics.service.CarInfoService;
import com.spark.lola.logistics.service.DriverInfoService;
import com.spark.lola.support.common.constant.CommonConstant;
import com.spark.lola.support.common.entity.ShiroUser;
import com.spark.lola.support.common.util.DataBeanUtils;
import com.spark.lola.support.common.util.ResponseBean;
import com.spark.lola.support.mybatis.controller.BaseController;
import com.spark.lola.support.mybatis.entity.QueryParam;
import com.spark.lola.support.wms.cache.CollectionCache;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author: Zhi-peng wang
 * @date: 2020/04/24 16:12
 * 驾驶员信息接口
 **/
@RestController
@RequestMapping("/api/logistics/driver")
@Api(value = "/api/logistics/driver", tags = "驾驶员信息接口")
public class DriverInfoController extends BaseController {

    @Autowired
    private DriverInfoService driverInfoService;

    @Autowired
    private CarInfoService carInfoService;

    @ApiOperation(value = "分页查询驾驶员信息")
    @RequiresPermissions(value = "m5120")
    @RequestMapping(value = "/findBy", method = RequestMethod.POST)
    public ResponseBean findPage(@RequestBody QueryParam<DriverInfo> queryParam) {
        IPage<DriverInfo> driverInfoIPage = driverInfoService.findPage(queryParam);
        driverInfoIPage.getRecords().forEach(driverInfo -> {
            driverInfo.setShiroUser(CollectionCache.employees.get(driverInfo.getEmpId()));
        });
        return ResponseBean.success(driverInfoIPage);
    }

    @ApiOperation(value = "获取驾驶员信息详情")
    @ApiImplicitParam(name = "id", value = "驾驶员信息id", required = true, dataType = "long", paramType = "path")
    @RequiresPermissions(value = "m5124")
    @RequestMapping(value = "/findInfo/{id}", method = RequestMethod.GET)
    public ResponseBean findInfo(@PathVariable long id, @SessionAttribute ShiroUser shiroUser) {
        DriverInfo driverInfo = new DriverInfo();
        if (id != 0) {
            driverInfo = driverInfoService.findInfo(id);
            driverInfo.setShiroUser(CollectionCache.employees.get(driverInfo.getEmpId()));
        }
        return ResponseBean.success(driverInfo);
    }

    @ApiOperation(value = "获取账号列表")
    @RequestMapping(value = "/findEmpMap")
    public ResponseBean findMap() {
        return ResponseBean.success(driverInfoService.findMap());
    }

    @ApiOperation(value = "获取驾驶员列表")
    @ApiImplicitParam(name = "key", value = "模糊查询字段，查询姓名", required = true, dataType = "String", paramType = "query")
    @RequestMapping(value = "/map/{isBind}")
    public ResponseBean map(@RequestParam String key, @PathVariable int isBind) {
        return ResponseBean.success(driverInfoService.selectMap(key, isBind));
    }

    @ApiOperation(value = "添加/修改驾驶员信息")
    @RequiresPermissions(value = {"m5121", "m5123"}, logical = Logical.OR)
    @RequestMapping(value = "/save", method = RequestMethod.POST)
    public ResponseBean save(@RequestBody DriverInfo driverInfo, @SessionAttribute ShiroUser shiroUser) {
        DriverInfo model = new DriverInfo();
        if (driverInfo.getId() != null) {
            model = driverInfoService.getById(driverInfo.getId());
            // 非修改项置空
            model.setUsed(null);
            model.setIsBind(null);
            // 系统修改项赋值
        } else {
            // 设置初始化项
            if (driverInfoService.empIdExists(driverInfo.getEmpId())) {
                return ResponseBean.error("该账户已被绑定");
            }
        }
        DataBeanUtils.buildUpdateBean(model, driverInfo);
        driverInfoService.saveOrUpdate(model);
        return ResponseBean.success(model);
    }

    @ApiOperation(value = "启用驾驶员")
    @ApiImplicitParam(name = "nos", value = "驾驶员信息id字符串集", required = true, dataType = "String", paramType = "query")
    @RequiresPermissions(value = "m5125")
    @RequestMapping(value = "/on", method = RequestMethod.GET)
    public ResponseBean on(@RequestParam String nos) {
        if (StringUtils.isBlank(nos)) {
            return ResponseBean.error("字符串集不能为空");
        }
        int count = driverInfoService.updateUsedByIds(CommonConstant.Y, nos);
        return ResponseBean.success(null, count);
    }

    @ApiOperation(value = "禁用驾驶员")
    @ApiImplicitParam(name = "nos", value = "驾驶员信息id字符串集", required = true, dataType = "String", paramType = "query")
    @RequiresPermissions(value = "m5126")
    @RequestMapping(value = "/un", method = RequestMethod.GET)
    public ResponseBean un(@RequestParam String nos) {
        if (StringUtils.isBlank(nos)) {
            return ResponseBean.error("字符串集不能为空");
        }
        int count = driverInfoService.updateUsedByIds(CommonConstant.N, nos);
        return ResponseBean.success(null, count);
    }

//    @ApiOperation(value = "检查绑定车辆")
//    @ApiImplicitParam(name = "id", value = "驾驶员信息id字符串集", required = true, dataType = "String", paramType = "query")
//    @RequiresPermissions(value = "m5126")
//    @RequestMapping(value = "/checkBindCar", method = RequestMethod.GET)
//    public ResponseBean checkBindCar() {
//
//    }

    @ApiOperation(value = "绑定车辆")
    @RequiresPermissions(value = "m5127")
    @RequestMapping(value = "/bind", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean bind(@RequestBody JSONObject jsonObject) throws Exception {
        long carId = jsonObject.getLongValue("carId");
        long driverId = jsonObject.getLongValue("driverId");
        Long oldCarId = driverInfoService.findCarId(driverId);
        if (oldCarId != null) {
            return ResponseBean.error("请解除已绑定车辆");
        }
        if (driverInfoService.carIdExists(carId)) {
            return ResponseBean.error("车辆已被驾驶员绑定");
        }
        // 修改车辆绑定状态
        int carUpdateCount = carInfoService.updateIsBind(LogisticsConstant.CarIsBind.Y_BIND, carId);
        if (carUpdateCount != 0) {
            // 绑定车辆
            int count = driverInfoService.bindCar(carId, LogisticsConstant.CarIsBind.Y_BIND, driverId);
            if (count != 0) {
                return ResponseBean.success(null, count);
            }
        }
        throw new Exception("绑定失败");
    }

    @ApiOperation(value = "解绑车辆")
    @RequiresPermissions(value = "m5128")
    @RequestMapping(value = "/unBind", method = RequestMethod.POST)
    @Transactional(rollbackFor = Exception.class)
    public ResponseBean unBind(@RequestBody JSONObject jsonObject) throws Exception {
        long carId = jsonObject.getLongValue("carId");
        long driverId = jsonObject.getLongValue("driverId");
        Long oldCarId = driverInfoService.findCarId(driverId);
        if (oldCarId == null) {
            return ResponseBean.error("未绑定车辆");
        }
        // 修改车辆绑定状态
        int carUpdateCount = carInfoService.updateIsBind(LogisticsConstant.CarIsBind.N_BIND, carId);
        if (carUpdateCount != 0) {
            // 绑定车辆
            int count = driverInfoService.bindCar(null, LogisticsConstant.CarIsBind.N_BIND, driverId);
            if (count != 0) {
                return ResponseBean.success(null, count);
            }
        }
        throw new Exception("解绑失败");
    }

    @ApiOperation(value = "删除驾驶员信息")
    @ApiImplicitParam(name = "nos", value = "车辆信息id集合", required = true, dataType = "Long", paramType = "query")
    @RequiresPermissions(value = "m5122")
    @RequestMapping(value = "/del", method = RequestMethod.GET)
    public ResponseBean del(@RequestParam(value = "nos") List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return ResponseBean.error("id字符串集不能为空");
        }
        if (ids.size() > 1) {
            return ResponseBean.error("禁止批量操作");
        }
        Long oldCarId = driverInfoService.findCarId(ids.get(0));
        if (oldCarId != null) {
            return ResponseBean.error("已绑定车辆，请解除绑定后操作");
        }
        driverInfoService.removeById(ids.get(0));
        return ResponseBean.success();
    }

}
